<template>
	<transition name="el-zoom-in-center">
		<div class="SHZY-preview-main">
			<div class="SHZY-common-page-header">
				<el-page-header @back="goBack" :content="!dataForm.id ? '新建' : '编辑'" />
				<div class="options">
					<el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading">确 定</el-button>
					<el-button @click="goBack">取 消</el-button>
				</div>
			</div>
			<div :style="{ margin: '0 auto', width: '100%' }">
				<el-row :gutter="15" class=" main">
					<el-form ref="tableForm" :model="dataForm" :rules="tableRules">
						<el-table :data="dataForm.list" size='mini'>
							<el-table-column type="index" width="50" label="序号" align="center" />
							<el-table-column prop="type" label="报检类型" min-width="150" :render-header="addRedStar">
								<template slot-scope="scope">
									<el-form-item :prop="'list.' + scope.$index + '.type'" :rules="tableRules.type">
										<el-select v-model='scope.row.type' placeholder='请选择' clearable
											:style='{ "width": "100%" }'>
											<el-option v-for="(item, index) in ipqcInspectionTypeData" :key="index"
												:label="item.fullName" :value="item.enCode"></el-option>
										</el-select>
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column prop="factoryId" label="工厂信息" min-width="250" >
								<template slot-scope="scope">
									<el-form-item :prop="'list.' + scope.$index + '.factoryId'"
										:rules="tableRules.factoryId">
										<SHZY-TreeSelect v-model="scope.row.factoryId" :options="treeData"
											:defaultExpandAll="false" placeholder="选择工厂信息" :disabled="false"
											@change="handleFactory(scope.row, arguments)" />
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column prop="materialCode" label="物料" min-width="250" :render-header="addRedStar">
								<template slot-scope="scope">
									<el-form-item :prop="'list.' + scope.$index + ''" :rules="tableRules.materialCode">
										<!-- <el-input v-model='scope.row.materialCode' placeholder='请输入' clearable
											:style='{ "width": "100%" }'>
										</el-input> -->
										<SHZY-select :list="materialOptions" v-model:bindValue="scope.row.materialCode"
											label="name" value="code" placeholder="请选择物料" isConcat concatSymbol=" / "
											@change="handleMaterialChange(scope.row, arguments)">
										</SHZY-select>
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column prop="processIdList" label="⼯序" min-width="250">
								<template slot-scope="scope">
									<el-form-item :prop="'list.' + scope.$index + '.processIdList'"
										:rules="tableRules.processIdList">
										<!-- <el-input v-model='scope.row.processIdList' placeholder='请输入' clearable
											:style='{ "width": "100%" }'>
										</el-input> -->
										<SHZY-TreeSelect v-model="scope.row.processResult" :options="scope.row.processData"
											lastLevel multiple placeholder="选择⼯序信息" :disabled="false"
											@change="handleProcess(scope.row, arguments)" />
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column prop="inspectionCase" label="检验⽅案" min-width="250" :render-header="addRedStar">
								<template slot-scope="scope">
									<el-form-item :prop="'list.' + scope.$index + ''" :rules="tableRules.inspectionCase">
										<SHZY-select :list="cardData" v-model:bindValue="scope.row.inspectionCase"
											label="name" value="id" placeholder="请选择检验⽅案">
										</SHZY-select>
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column prop="orderNo" label="⽣产订单号" min-width="140" :render-header="addRedStar">
								<template slot-scope="scope">
									<el-form-item :prop="'list.' + scope.$index + '.orderNo'" :rules="tableRules.orderNo">
										<el-input v-model='scope.row.orderNo' placeholder='请输入' clearable
											:style='{ "width": "100%" }'>
										</el-input>
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column prop="productionQty" label="⽣产数量" min-width="140" :render-header="addRedStar">
								<template slot-scope="scope">
									<el-form-item :prop="'list.' + scope.$index + '.productionQty'"
										:rules="tableRules.productionQty">
										<el-input v-model='scope.row.productionQty' placeholder='请输入' clearable
											:style='{ "width": "100%" }'>
										</el-input>
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column prop="employeeCode" label="检验员" min-width="140">
								<template slot-scope="scope">
									<el-form-item :prop="'list.' + scope.$index + '.employeeCode'"
										:rules="tableRules.employeeCode">
										<user-select v-model="scope.row.employeeCode" placeholder="检验员"
											@change="onChange(scope.row, arguments)" />
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column prop="date" label="报检日期" min-width="220" :render-header="addRedStar">
								<template slot-scope="scope">
									<el-form-item :prop="'list.' + scope.$index + ''" :rules="tableRules.date">
										<el-date-picker v-model='scope.row.date' placeholder='请选择'
											:disabled="scope.row.dayFlag == 'Y' || scope.row.hourFlag == 'Y'" clearable
											:style='{ "width": "100%" }' type='datetime' format='yyyy-MM-dd HH:mm:ss'
											value-format='timestamp'>
										</el-date-picker>
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column prop="dayFlag" label="按天生成" min-width="140" :render-header="addRedStar">
								<template slot-scope="scope">
									<el-form-item :prop="'list.' + scope.$index + '.dayFlag'" :rules="tableRules.dayFlag">
										<el-radio-group v-model='scope.row.dayFlag' size='small'
											@change="scope.row.dayValue = 0" :disabled="scope.row.hourFlag == 'Y'">
											<el-radio-button v-for="(item, index) in options1" :key="index"
												:label="item.id">{{ item.fullName }}</el-radio-button>
										</el-radio-group>
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column prop="dayValue" label="天" min-width="140" :render-header="addRedStar">
								<template slot-scope="scope">
									<el-form-item :prop="'list.' + scope.$index + ''" :rules="tableRules.dayValue">
										<el-input v-model='scope.row.dayValue' placeholder='请输入'
											:disabled="scope.row.dayFlag == 'N'" clearable :style='{ "width": "100%" }'>
										</el-input>
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column prop="hourFlag" label="按小时生成" min-width="140" :render-header="addRedStar">
								<template slot-scope="scope">
									<el-form-item :prop="'list.' + scope.$index + '.hourFlag'" :rules="tableRules.hourFlag">
										<el-radio-group v-model='scope.row.hourFlag' size='small'
											@change="scope.row.hourValue = 0" :disabled="scope.row.dayFlag == 'Y'">
											<el-radio-button v-for="(item, index) in options1" :key="index"
												:label="item.id">{{ item.fullName }}</el-radio-button>
										</el-radio-group>
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column prop="hourValue" label="小时" min-width="140" :render-header="addRedStar">
								<template slot-scope="scope">
									<el-form-item :prop="'list.' + scope.$index + ''" :rules="tableRules.hourValue">
										<el-input v-model='scope.row.hourValue' placeholder='请输入'
											:disabled="scope.row.hourFlag == 'N'" clearable :style='{ "width": "100%" }'>
										</el-input>
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column prop="closeFlag" label="⾃动关闭" min-width="140" :render-header="addRedStar">
								<template slot-scope="scope">
									<el-form-item :prop="'list.' + scope.$index + '.closeFlag'"
										:rules="tableRules.closeFlag">
										<el-radio-group v-model='scope.row.closeFlag' size='small'>
											<el-radio-button v-for="(item, index) in options1" :key="index"
												:label="item.id">{{ item.fullName }}</el-radio-button>
										</el-radio-group>
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column prop="remark" label="备注" min-width="140">
								<template slot-scope="scope">
									<el-form-item :prop="'list.' + scope.$index + '.remark'" :rules="tableRules.remark">
										<el-input v-model='scope.row.remark' placeholder='请输入' clearable
											:style='{ "width": "100%" }'>
										</el-input>
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column label="操作" width="100" fixed="right">
								<template slot-scope="scope">
									<el-button type="text" @click="handleCopy(scope.row)">复制</el-button>
									<el-button class="SHZY-table-delBtn" size="mini" type="text"
										@click="handleDel(scope.$index, scope.row)">删除</el-button>
								</template>
							</el-table-column>
						</el-table>
					</el-form>
					<div class="table-actions" @click="addHandle()">
						<el-button type="text" icon="el-icon-plus">添加报检单</el-button>
					</div>
				</el-row>
			</div>
		</div>
	</transition>
</template>
<script>
import { getIpqcInspectionInfo, createIpqcInspection, updateIpqcInspection, getArtrouteSelector } from '@/api/q1/business/ipqcInspection'
import factorystructureAPI from "@/api/q1/basedata/factorystructure";
import { getMaterialAll } from '@/api/q1/basedata/material';
import { getCheckcardAll } from '@/api/q1/basedata/inspectionsCardList'
export default {
	components: {},
	props: [],
	data() {
		const materialCodeValidator = (rule, value, callback) => {
			if (!value || (value.materialCode.trim().length == 0 && value.inspectionCase.trim().length == 0)) {
				callback(new Error("请选择物料或者检验方案"));
			} else {
				callback();
			}
		};
		const inspectionCaseValidator = (rule, value, callback) => {
			if (!value || (value.materialCode.trim().length == 0 && value.inspectionCase.trim().length == 0)) {
				callback(new Error("请选择检验方案或者物料"));
			} else {
				callback();
			}
		};
		const dateValidator = (rule, value, callback) => {
			if (!value || (value.date.length == 0 && value.dayFlag == "N" && value.hourFlag == "N")) {
				callback(new Error("请选择报检日期"));
			} else {
				callback();
			}
		};
		const dayValueValidator = (rule, value, callback) => {
			if (!value || (value.dayValue.length == 0 && value.dayFlag == "Y")) {
				callback(new Error("请输入天"));
			} else {
				var _reg = /^\d+$/
				if (!_reg.test(value.dayValue)) {
					callback(new Error("请输入正确的数字"));
				} else {
					callback();
				}
			}
		};
		const hourValueValidator = (rule, value, callback) => {
			if (!value || (value.hourValue.length == 0 && value.hourFlag == "Y")) {
				callback(new Error("请输入小时"));
			} else {
				var _reg = /^\d+$/
				if (!_reg.test(value.hourValue)) {
					callback(new Error("请输入正确的数字"));
				} else {
					callback();
				}
			}
		};
		return {
			btnLoading: false,
			loading: false,
			visible: false,
			ipqcInspectionTypeData: [],
			treeData: [],
			materialOptions: [],
			processData: [],
			cardData: [],
			dataForm: {
				list: [
					// {
					// 	id: '',
					// 	code: '',
					// 	date: '',
					// 	type: '',
					// 	factoryId: '',
					// 	workshopId: '',
					// 	teamId: '',
					// 	workshopSectionId: '',
					// 	stationId: '',
					// 	materialCode: '',
					// 	processData: [],
					// 	processResult: '',
					// 	processIdList: '',
					// 	inspectionCase: '',
					// 	productionQty: 0,
					// 	employeeCode: '',
					// 	employeeName: '',
					// 	orderNo: '',
					// 	remark: '',
					// 	status: 0,
					// 	overdue: 0,
					// 	closeFlag: "N",
					// 	dayFlag: "N",
					// 	dayValue: 0,
					// 	hourFlag: "N",
					// 	hourValue: 0,
					// }
				]
			},
			tableRules: {
				type: [{ required: true, message: '请选择报检类型', trigger: '"blur"' },],
				// factoryId: [{ required: true, message: '请选择工厂信息', trigger: '"blur"' },],
				materialCode: [{ required: true, validator: materialCodeValidator, trigger: '"blur"' }],
				inspectionCase: [{ required: true, validator: inspectionCaseValidator, trigger: '"blur"' }],
				orderNo: [{ required: true, message: '请输入⽣产订单号', trigger: '"blur"' },],
				productionQty: [
					{ required: true, message: '请输入⽣产数量', trigger: '"blur"' },
					{ pattern: /^\d+$/, message: '请输入正确的数字', trigger: '"blur"' },
				],
				// employeeCode: [{ required: true, message: '请选择检验员', trigger: '"blur"' },],
				date: [{ required: true, validator: dateValidator, trigger: '"blur"' }],
				dayValue: [
					{ required: true, validator: dayValueValidator, trigger: '"blur"' },
				],
				hourValue: [
					{ required: true, validator: hourValueValidator, trigger: '"blur"' },
				],
			},
			typeOptions: [{ 'fullName': "选项一", 'id': "1" }, { 'fullName': "选项二", 'id': "2" }],
			options1: [{ 'fullName': "关闭", 'id': "N" }, { 'fullName': "开启", 'id': "Y" }],
		}
	},
	computed: {},
	watch: {},
	created() {
		this.getDictionaryData()
	},
	mounted() {
	},
	methods: {
		addRedStar(h, { column }) {
			return [
				h("span", { style: "color: red" }, "*"),
				h("span", " " + column.label),
			];
		},
		goBack() {
			this.$emit('refresh')
		},
		init(id) {
			this.dataForm.id = id || 0;
			this.visible = true;
			this.$nextTick(() => {
				this.$refs['tableForm'].resetFields();
				factorystructureAPI.getDictionaryTypeSelector(0).then(res => {

					this.treeData = res.data.list
				})
				getMaterialAll().then(res => {
					this.materialOptions = res.data.list;
				});
				getArtrouteSelector(0).then(res => {
					this.processData = res.data.list
				})
				getCheckcardAll().then(res => {
					this.cardData = res.data.list;
				});
				if (this.dataForm.id) {
					getIpqcInspectionInfo(this.dataForm.id).then(res => {
						this.dataForm = res.data;
					})
				}
			});
		},
		getDictionaryData() {
			this.$store.dispatch('base/getDictionaryData', { sort: 'ipqcInspectionType' }).then((res) => {
				this.ipqcInspectionTypeData = res
			})
		},
		getFactoryInfo(parentId, row, data) {
			data.some(element => {
				if (element.id == parentId) {
					if (element.type == "Workshop") {
						row.workshopId = element.id
					} else if (element.type == "Team") {
						row.teamId = element.id
					} else if (element.type == "Section") {
						row.workshopSectionId = element.id
					} else if (element.type == "Station") {
						row.stationId = element.id
					}
					if (element.parentId != "") {
						this.getFactoryInfo(element.parentId, row, this.treeData)
					} else {
						return true
					}
				} else {
					if (element.hasChildren) {
						this.getFactoryInfo(parentId, row,element.children)
					}
				}
			})
		},
		handleFactory(row, data) {
			row.workshopId = ""
			row.teamId = ""
			row.workshopSectionId = ""
			row.stationId = ""
			if (!data[1]) {
				return
			}
			//Workshop, Team, Section
			if (data[1].type == "Workshop") {
				row.workshopId = data[1].id
			} else if (data[1].type == "Team") {
				row.teamId = data[1].id
			} else if (data[1].type == "Section") {
				row.workshopSectionId = data[1].id
			} else if (data[1].type == "Station") {
				row.stationId = data[1].id
			}
			if (data[1].parentId != "")
				this.getFactoryInfo(data[1].parentId, row, this.treeData)
		},
		handleMaterialChange(row, data) {
			getArtrouteSelector(data[0]).then(res => {
				row.processData = res.data.list
			})
		},
		handleProcess(row, data) {
			row.processIdList = data[0].join(',')
		},
		onChange(row, data) {
			if (!data[1]) return row.employeeName = ''
			row.employeeName = data[1].fullName
		},
		handleCopy(row) {
			let index = this.dataForm.list.length, item = {}
			item = {
				...row
			}
			item.index = index
			this.dataForm.list.push(item)
		},
		handleDel(index, row) {
			this.dataForm.list.splice(index, 1)
		},
		addHandle() {
			this.dataForm.list.push({
				id: '',
				code: '',
				date: '',
				type: '',
				factoryId: '',
				workshopId: '',
				teamId: '',
				workshopSectionId: '',
				stationId: '',
				materialCode: '',
				processData: this.processData,
				processResult: '',
				processIdList: '',
				inspectionCase: '',
				productionQty: 0,
				employeeCode: '',
				employeeName: '',
				orderNo: '',
				remark: '',
				status: 0,
				overdue: 0,
				closeFlag: "N",
				dayFlag: "N",
				dayValue: 0,
				hourFlag: "N",
				hourValue: 0,
			})
		},
		dataFormSubmit() {
			if (this.dataForm.list.length == 0) {
				this.$message({
					type: 'error',
					message: '请添加报检信息',
					duration: 1500,
				})
				return
			}
			this.$refs['tableForm'].validate((valid) => {
				if (valid) {
					this.btnLoading = true;
					const formMethod = !this.dataForm.id ? createIpqcInspection : updateIpqcInspection;

					formMethod(this.dataForm.list).then((res) => {
						this.btnLoading = false;
						this.$message({
							message: res.msg,
							type: 'success',
							duration: 1000,
							onClose: () => {
								this.visible = false,
									this.$emit('refresh', true)
							}
						})
					}).catch((res) => {
						this.btnLoading = false;
					})
				}
			})
		},
	}
}
</script>
